<?php
declare(strict_types=1);
namespace SixShop\Eav\Controller;

use SixShop\Core\Request;
use SixShop\Eav\Entity\EavAttributeEntity;
use SixShop\Eav\Entity\EavValueEntity;
use think\Response;

use function SixShop\Core\success_response;

class EntityAttributeController
{
    public function index(Request $request, EavAttributeEntity $entity): Response
    {
        $entityTypeID = $request->get('entity_type_id/d');
        return success_response($entity->where('entity_type_id', $entityTypeID)->select());
    }

    public function save(Request $request, EavAttributeEntity $entity): Response
    {
        $data = $request->post();
        $entityObject = $entity->withTrashed()->where([
            'entity_type_id' => $data['entity_type_id'],
            'attribute_code' => $data['attribute_code'
            ]])->findOrEmpty();
        if (!$entityObject->isEmpty()) {
            $entityObject->restore();
            $data['id'] = $entityObject['id'];
        }
        return success_response($entityObject->save($data));
    }

    public function update(int $id, Request $request, EavAttributeEntity $entity): Response
    {
        $data = $request->post();
        return success_response($entity->where('id', $id)->update($data));
    }

    public function delete(int $id, EavAttributeEntity $entity, EavValueEntity $entityValue): Response
    {
        $entity->destroy($id);
        $entityValue->where('attribute_id', $id)->delete();

        return success_response();
    }
}